package com.itheima.tlias08_14.controller;

import com.itheima.tlias08_14.annotation.Log;
import com.itheima.tlias08_14.config.OssClient;
import com.itheima.tlias08_14.utils.ResultUtil;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;


//AccessKey ID : LTAI5tQaMHSWUx8Qpv6niTv6
//AccessKey Secret : k2jGIbF5ClvNRy2I688kPP2aJY3hHQ
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {

    @Resource
    OssClient oss;

    @PostMapping
    @Log
    public ResultUtil upload(MultipartFile file) throws IOException {//MultipartFile 用于接收上传的文件
        //获取参数名
        log.info("参数名：{}", file.getName());
        //获取文件名
        log.info("文件名：{}", file.getOriginalFilename());
        //获取到的本地上传的文件名
        String filename = file.getOriginalFilename();
        //String suffix = filename.substring(filename.lastIndexOf("."));
        //阿里云OSS访问路径
        //String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
        //String endpoint = config.getEndpoint();
        //填写Bucket名称。
        //String bucketName = "test-dmr84";
        //String bucketName = config.getBucketName();
        //为了防止储存的文件名重复，需要给文件重命名
        //String uuid = UUID.randomUUID().toString();
        // 填写Object完整路径，完整路径中不能包含Bucket名称

       // String objectName = uuid + suffix;//获取到的文件存储的文件名

        // 创建OSSClient实例。
        // 指定上传的文件路径 和 accessKeyId 和 accessKeySecret。
        //OSS ossClient = new OSSClientBuilder().build(config.getEndpoint(), config.getAccessKeyId(), config.getAccessKeySecret());
        //OSS ossClient = new OSSClientBuilder().build(endpoint,
        //"LTAI5tQaMHSWUx8Qpv6niTv6", "k2jGIbF5ClvNRy2I688kPP2aJY3hHQ");

        //public PutobjectResult putobject(String bucketName, String key, InputStream input)
//        //putObject请求。将获取到的本地文件上传到指定的阿里云路径的Bucket中，并以随机生成的uuid作为文件名存放
//        try {
//            ossClient.putObject(bucketName, objectName, file.getInputStream());//文件数据上传到阿里云Bucket中
//            //String url = "https://" + bucketName + ".oss-cn-hangzhou.aliyuncs.com/" + objectName;
//            String url = config.getUrl() + objectName;
//            return ResultUtil.success(new StringBuilder(url));
//        } catch (IOException e) {
//            throw new RuntimeException(e);
//        }
        String url = oss.upload(filename, file.getInputStream());
        return ResultUtil.success(new StringBuilder(url));
    }

}

